<template>
	<view class="container">
		<!-- 顶部返回按钮 -->
<!-- 		<view class="back-btn" @click="handleBack">
			<text class="icon">×</text>
		</view> -->

		<!-- 主内容区 -->
		<view class="content">
			<text class="title">{{txt}}</text>
			<text class="tip" v-if="!passShow">若手机号未注册，我们将自动注册</text>

			<!-- 输入区 -->
			<view class="input-area">
				<input class="phone-input" placeholder="请输入手机号" type="number" maxlength="11" v-model="phone" />
		<!-- 		<view class="code-btn" :style="{ backgroundColor: phone.length === 11 ? '#FEF4E8' : '#f5f5f5' }" @click="getCode" >
					<text class="code-text">获取验证码</text>
				</view> -->
				<view class="code-btn" v-if="!passShow" :style="{ backgroundColor: phone.length === 11 ? '#FEF4E8' : '#f5f5f5', cursor: countdown > 0 ? 'not-allowed' : 'pointer' }" @click="getCode" :disabled="countdown > 0" >
				    <text class="code-text">
				      {{ countdown > 0 ? `重新发送(${countdown})` : '获取验证码' }}
				    </text>
				  </view>
			</view>
			<view class="input-area">
				<input v-if="passShow" class="code-input" type="password" password="true" placeholder="请输入密码" v-model="password" />
				<input v-if="!passShow" class="code-input" placeholder="请输入验证码" type="text" maxlength="4" v-model="codes" />
			</view>
			<view class="login-btn" @click="login"> 登录 </view>
			<view class="sms-btn" @click="passLogin" v-if="!passShow"> 密码登录 </view>
			<view class="sms-btn" @click="codesLogin" v-if="passShow"> 验证码登录 </view>
		</view>
		<!-- 底部协议 -->
		<view class="footer">
			<text class="agree-text"> 
				<text>登录即同意</text>
				<text class="link" @click="userxieyi">《用户协议》</text>、
				<text class="link" @click="xieyi">《隐私政策》</text>
			</text>
		</view>
	</view>
</template>

<script setup>
import { onMounted, ref } from 'vue';

const phone = ref('');
const codes = ref('');
const password = ref('');
const baseURL = ref(getApp().globalData.baseUrl);

const countdown = ref(0)    // 倒计时秒数
const isSending = ref(false) // 发送状态
let timer = null            // 计时器对象
let bgColor = ref("#F56822")
let txt = ref('短信验证码登录')
let passShow = ref(false)

// 发送验证码逻辑
const getCode = async () => {
  if (!/^1[3-9]\d{9}$/.test(phone.value)) {
  	uni.showToast({ title: '请输入正确手机号', icon: 'none' });
    return false
  }
  try {
    isSending.value = true
    uni.request({
    	url: baseURL.value + '/api/index/telcode',
    	method: 'GET',
    	data:{phone:phone.value,appid:uni.getStorageSync('appid')},
    	header: { 'Content-Type': 'application/json' },
    	success: (res) => {
    		  if( res.data.status == 100 ){
    			  startCountdown()
    			  uni.showToast({ title: '验证码已发送' });
    		  } else {
    			  uni.showToast({ title: res.data.message, icon: 'none' });
    		  }
    	},
    	fail: (err) => {
    		console.error('请求失败:', err);
    	}
    })
    
  } catch (error) {
  	uni.showToast({ title: '发送失败', icon: 'none' });
  } finally {
    isSending.value = false
  }
}

// 倒计时逻辑（优化网页7方案）
const startCountdown = () => {
  countdown.value = 60
  timer = setInterval(() => {
    if (countdown.value <= 0) {
      clearInterval(timer)
      return
    }
    countdown.value--
  }, 1000)
}

// 组件卸载时清除定时器（参考网页7）
onMounted(() => {
  if (timer) clearInterval(timer)
});


const navigateToAgreement = () => {
  uni.navigateTo({ url: '/pages/agreement/agreement' });
};

const navigateToPrivacy = () => {
  uni.navigateTo({ url: '/pages/privacy/privacy' });
};
const xieyi = ()=>{
	uni.navigateTo({url: '/pages/user/xieyi'})
};
const userxieyi = ()=>{
	uni.navigateTo({url: '/pages/user/notice'})
};
const login = ()=>{
	if( !passShow.value ){
		uni.request({
			url: baseURL.value + '/api/index/login',
			method: 'GET',
			data:{phone:phone.value,code:codes.value},
			header: { 'Content-Type': 'application/json' },
			success: (res) => {
				  if( res.data.status == 100 ){
					  console.log(res.data)
					  uni.showToast({ title: '登录成功！' });
					  setTimeout(function(){
						  uni.setStorageSync('phone',phone.value)
						  uni.setStorageSync('isLogin',true)
						  uni.reLaunch({url: '/pages/user/user'})
						  uni.setStorageSync('appid',res.data.data.appid)
					  },1000)
				  } else {
					  uni.showToast({ title: res.data.message, icon: 'none' });
				  }
			},
			fail: (err) => {
				console.error('请求失败:', err);
			}
		})
	} else {
		uni.request({
			url: baseURL.value + '/api/index/accountLogin',
			method: 'GET',
			data:{account:phone.value,password:password.value},
			header: { 'Content-Type': 'application/json' },
			success: (res) => {
				  if( res.data.status == 100 ){
					  console.log(res.data)
					  uni.showToast({ title: '登录成功！' });
					  setTimeout(function(){
						  uni.setStorageSync('phone',phone.value)
						  uni.setStorageSync('isLogin',true)
						  uni.reLaunch({url: '/pages/user/user'})
						  uni.setStorageSync('appid',res.data.data.appid)
					  },1000)
				  } else {
					  uni.showToast({ title: res.data.msg, icon: 'none' });
				  }
			},
			fail: (err) => {
				console.error('请求失败:', err);
			}
		})
	}
};
const passLogin = ()=>{
	txt.value = "密码登录"
	passShow.value = true
};
const codesLogin = ()=>{
	txt.value = "短信验证码登录"
	passShow.value = false
}
</script>

<style>
.container {
  padding: 24rpx;
  height: 100vh;
  position: relative;
}

.back-btn {
  width: 100rpx;
  height: 100rpx;
  display: flex;
  align-items: start;
  justify-content: center;
}

.icon {
  font-size: 80rpx;
  color: #333;
}

.content {
  margin-top: 20rpx;
}

.title {
  font-size: 44rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 24rpx;
}

.tip {
  font-size: 26rpx;
  color: #999;
  display: block;
  margin-bottom: 80rpx;
}
.login-btn{
  display: flex;
  flex-direction: row;
  align-items: center;
  width: 90%;
  margin-top: 30rpx;
  margin-left: 5%;
  border-radius: 10rpx;
  text-align: center;
  height: 80rpx;
  color: rgb(235,113,67);border: 1rpx solid rgb(235,113,67);background: #fff;display: block;line-height: 80rpx;
}
.input-area {
  display: flex;
  flex-direction: row;
  align-items: center;
  border-bottom: 2rpx solid #eee;
}

.phone-input {
  flex: 1;
  height: 80rpx;
  font-size: 32rpx;
  padding-left: 20rpx;
}
.code-input {
  flex: 1;
  height: 80rpx;
  font-size: 32rpx;
  padding-left: 20rpx;
  margin-top: 30rpx;
}

.code-btn {
  width: 30%;
  height: 40rpx;
  border-radius: 10rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
  background: rgb(254,244,232);
  padding: 20rpx;
  margin-bottom: 20rpx;
}

.code-text {
  color: rgb(235,113,67);
  font-size: 28rpx;
}

.footer {
  position: fixed;
  bottom: 60rpx;
  left: 0;
  right: 0;
  text-align: center;
}

.agree-text {
  font-size: 24rpx;
  color: #999;
  text-align: center;
}

.link {
  color: #EA752E;
}
.sms-btn{
	width: 90%;
	margin-left: 5%;
	text-align: center;
	height: 80rpx;
	text-align: center;
	color: #999;
	line-height: 120rpx;
}
</style>